package com.ilxqx.framework.controller;

import com.ilxqx.framework.util.ResultUtils;
import com.ilxqx.framework.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static org.apache.http.HttpStatus.*;

/**
 * 框架全局错误控制器
 * @author venus
 */
@Api("错误处理控制器")
@Controller
@RequestMapping("${server.error.path}")
@Slf4j
public class FrameworkErrorController implements ErrorController {

    private final ErrorAttributes errorAttributes;

    @Autowired
    public FrameworkErrorController(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    /**
     * Returns the path of the error page.
     *
     * @return the error path
     */
    @Override
    public String getErrorPath() {
        return null;
    }

    @RequestMapping(produces = "text/html")
    public String handlePageError() {
        return "security/login";
    }

    @ApiOperation("响应错误信息（JSON）")
    @ApiResponses({
            @ApiResponse(code = SC_OK, message = "处理成功"),
            @ApiResponse(code = SC_BAD_REQUEST, message = "请求参数没设置好"),
            @ApiResponse(code = SC_NOT_FOUND, message = "未能找到"),
            @ApiResponse(code = SC_UNAUTHORIZED, message = "没有授权，没有登录"),
            @ApiResponse(code = SC_FORBIDDEN, message = "请求遭到拒绝，一般是没有权限"),
            @ApiResponse(code = SC_METHOD_NOT_ALLOWED, message = "请求方法不支持"),
            @ApiResponse(code = SC_INTERNAL_SERVER_ERROR, message = "服务器内部错误"),
    })
    @RequestMapping
    @ResponseBody
    public ResponseEntity<ResultVO> handleJsonError(HttpServletRequest request) {
        WebRequest webRequest = new ServletWebRequest(request);
        Map<String, Object> attributes = errorAttributes.getErrorAttributes(webRequest, false);
        return new ResponseEntity<>(ResultUtils.failure((String) attributes.get("message")), HttpStatus.valueOf((Integer) attributes.get("status")));
    }

}
